<template>
  <div class="qyui-cell row qyui-container">
    <div class="qyui-cell" style="height:35px">
      <el-button type="primary" icon="Plus" plain @click="handleAddDataSource">
        新增
      </el-button>
      <el-button type="danger" icon="Delete" plain @click="handleDeleteDataSource">
        删除
      </el-button>
    </div>
    <div class="qyui-cell col">
      <div class="qyui-cell" style="width:300px">
        <div class="qyui-cell row">
          <el-tree
            :data="treeData"
            default-expand-all
            node-key="id"
            :expand-on-click-node="false"
            highlight-current
            @node-click="handleNodeClick"
          >
          </el-tree>
        </div>
      </div>
      <div class="qyui-cell row">
        <el-form ref="form" class="withRules" label-width="100px" :model="form" :rules="dataSourceRules">
          <template v-if="formData.ID!==''">
            <el-form-item label="ID" prop="ID">
              <el-input v-model="formData.ID" type="text" disabled></el-input>
            </el-form-item>
            <el-form-item label="数据源名称" prop="Name">
              <el-input v-model="formData.Name" type="text" placeholder="请输入数据源名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="SQL文本" prop="SQLString">
              <codemirror
                v-model="formData.SQLString" :style="{ height: '400px', width: '100%' }" :autofocus="true"
                :extensions="extensions"
              >
              </codemirror>
            </el-form-item>
            <el-form-item label="">
              <el-button type="success" icon="Finished" plain @click="checkDataSource">
                验证
              </el-button>
              <el-button type="primary" icon="Finished" plain @click="handleSave">
                保存
              </el-button>
            </el-form-item>
          </template>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { Codemirror } from 'vue-codemirror';
import { sql } from '@codemirror/lang-sql';
export default {
  components: { Codemirror },
  inject: ['manager'],
  data: function () {
    return {
      currentDataTableIndex: -1,
      dataSourceRules: {},
      sqleditor: null,
      extensions: [sql()],
      formData: {
        ID: '',
        Name: '',
        SQLString: '',
        Fields: [],
      },
    };
  },
  computed: {
    treeData() {
      const list = [];
      this.manager.allDataSets.forEach(item => {
        const children = [];
        item.Fields.forEach(field => {
          children.push({ id: field.Name, type: 'field', label: field.Name });
        });
        list.push({ id: item.Name, label: item.Name, type: 'table', children: children });
      });
      return list;
    },
  },
  mounted: function () {
    if (this.manager.allDataSets.length > 0) {
      this.handleSelectDataSet(0);
    }
  },
  methods: {
    handleNodeClick(data, node) {
      if (data.type === 'table') {
        const index = this.manager.allDataSets.findIndex(a => a.Name === data.label);
        this.currentDataTableIndex = index;
        this.handleSelectDataSet(index);
      }
    },
    handleSelectDataSet(index) {
      this.formData.ID = this.manager.allDataSets[index].ID;
      this.formData.Name = this.manager.allDataSets[index].Name;
      this.formData.SQLString = this.manager.allDataSets[index].SQLString;
      this.formData.Fields = this.manager.allDataSets[index].Fields;
    },
    handleAddDataSource() {
      this.formData.ID = -1;
      this.formData.Name = '';
      this.formData.SQLString = '';
      this.formData.Fields = [];
    },
    async handleDeleteDataSource() {
      const res = await this.$http({
        url: 'api/ZSReport/DeleteRDLDataSource',
        method: 'post',
        data: {
          id: this.formData.ID,
        },
      });
      if (res) {
        this.$message({
          type: 'success',
          message: '删除成功',
        });
        this.manager.allDataSets.splice(this.currentDataTableIndex, 1);
        this.currentDataTableIndex--;
      }
    },
    async checkDataSource() {
      const data = {
        isProc: false,
        sql: this.formData.SQLString,
        parameters: this.manager.Parameters,
      };
      const res = await this.$http({ url: 'api/ZSReport/GetRDLDataSourceResult', method: 'post', data });
      if (res) {
        this.$message({
          type: 'success',
          message: '验证成功',
        });
        this.formData.Fields = res.list;
      }
    },
    async handleSave() {
      const data = {
        id: this.formData.ID,
        reportId: this.manager.reportId,
        name: this.formData.Name,
        sql: this.formData.SQLString,
        fields: this.formData.Fields,
        isProc: false,
      };
      const res = await this.$http({ url: 'api/ZSReport/SaveRDLDataSource', method: 'post', data });
      if (res) {
        this.$message({
          type: 'success',
          message: '保存成功',
        });
        if (res.id) {
          this.formData.ID = res.id;
          this.manager.allDataSets.push(
            {
              ID: this.formData.ID,
              Name: this.formData.Name,
              SQLString: this.formData.SQLString,
              Fields: this.formData.Fields,
            },
          );
        } else {
          const index = this.manager.allDataSets.findIndex(a => a.ID === this.formData.ID);
          if (index > -1) {
            this.manager.allDataSets[index].Name = this.formData.Name;
            this.manager.allDataSets[index].SQLString = this.formData.SQLString;
            this.manager.allDataSets[index].Fields = this.formData.Fields;
          }
        }
      }
    },
  },
};
</script>

<style>

</style>
